package br.com.nirvana.loteria.input;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import br.com.nirvana.loteria.util.Loteria;


public class HtmToCSV {

	public void convert(File htmFile, File resultFile, Loteria loteria) {
			int balls = 0;
			switch (loteria) {
			case MEGASENA:
				balls = 6;
				break;
			case LOTOMANIA:
				balls = 20;
				break;
			case LOTOFACIL:
				balls = 15;
				break;
			}
		try {
			BufferedReader reader = new BufferedReader(new FileReader(htmFile));
			String line = null;
			do {
				line = reader.readLine();
				if (line.matches("</tr>")) {
					break;
				}
			} while (line != null);
			int cont = 0;
			BufferedWriter writer = new BufferedWriter(new FileWriter(
					resultFile));
			while ((line = reader.readLine()) != null) {
				if (line.contains("table")) {
					break;
				}
				if (line.matches("<td.*?>")) {
					if (cont == 0) {
						cont++;
						writer.append(line.substring(4, line.indexOf("</td>")));
					} else if (cont == 1) {
						cont++;
					} else if (cont > 1 && cont < balls+2) {
						writer.append(",");
						cont++;
						writer.append(line.substring(4, line.indexOf("</td>")));
					}
				}
				if (line.matches("</tr>")) {
					cont = 0;
					writer.append("\n");
					writer.flush();
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public boolean isCSVValid(Loteria loteria, File csvFile){
		int balls = 0;
		switch (loteria) {
		case MEGASENA:
			balls = 6;
			break;
		case LOTOMANIA:
			balls = 20;
			break;
		case LOTOFACIL:
			balls = 15;
			break;
		}
		try {
			String line = null;
			String[] columns = null;
			int cont = 1;
			BufferedReader reader = new BufferedReader(new FileReader(csvFile));
			while((line = reader.readLine()) != null){
				columns = line.split(",");
				if (columns.length != balls+1) {
					return false;
				} else if(Integer.parseInt(columns[0]) != cont){
					return false;
				}
				cont++;
				for(int i =1; i < columns.length; i++){
					if(!columns[i].matches("\\d\\d")){
						return false;
					}
				}
			}
		} catch(Exception ex) {
			return false;
		}
		return true;
	}
}
